package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var Socket = &socket{}

type socket struct {
	User map[*websocket.Conn]bool
	Status bool
}

var SocketGrader = websocket.Upgrader{
	CheckOrigin: func (r *http.Request) bool {
		return true
	},
}

type MessageFormat struct {
	Type string `json:"type"`
	Data string `json:"data"`
}

func Message(c *gin.Context) {

	conn, _ := SocketGrader.Upgrade(c.Writer, c.Request, nil)

	if Socket.Status == false {
		Socket.User = make(map[*websocket.Conn]bool)
		Socket.Status = true
	}

	Socket.User[conn] = true

	for {
		_, data, err := conn.ReadMessage()
		if err != nil {
			break
		}

		for user := range Socket.User {
			err := user.WriteMessage(1, data)
			if err != nil {
				user.Close()
				delete(Socket.User, user)
			}
		}
	}
}
